#!/usr/bin/env/ python3

import sys
import re

# 1. 为$开头的行添加代码块
# 2. 删除开头的#:

url_regex = r'\{%\s*url\s+([^\s]+)\s*(\s+[^\s]+)?%}'

class TextRenderer:
    @staticmethod
    def url(u):
        return u

    def render(self, text):
        return re.sub(url_regex,
                lambda m:m.groups()[0].strip(),
                text)


class MarkdownRenderer:
    @staticmethod
    def url(u, label):
        u = re.sub(r'/+', '/', '/web/' + u.strip())
        r = '[%s](%s)' % (label.strip() if label else u, u)
        return r

    def render(self, s):
        res = []
        sp = s.split('\n')
        inside_code = False

        def replace(m):
            return MarkdownRenderer.url(m.groups()[0], m.groups()[1])

        i = 0
        while i < len(sp):
            line = sp[i]
            if re.match(r'```\w*$', line):
                inside_code = not inside_code

            # 处理url
            line = re.sub(url_regex,
                    replace,
                    line)

            # 处理'$'开头的行
            if not inside_code and line.startswith('$'):
                t = []
                while i < len(sp) and line.startswith('$'):
                    t.append(line)
                    i += 1
                    line = sp[i]
                res.append('```bash')
                res.extend(t)
                res.append('```')
                continue

            # 处理'#:'开头的行
            if not inside_code and line.startswith('#:'):
                res.append(re.sub(r'^#: ?', '', line))
                i += 1
                continue

            # 其余照常输出
            res.append(line)
            i += 1

        return '\n'.join(res)


def test_convert():
    s1 = """
# 测试在代码块中的$

```cpp
$ sudo ls
```
"""
    s1_o = convert(s1)
    assert (s1_o == s1)

    s2 = """
# 测试代码块外的$

$ sudo ls
$ pwd

```
$ sudo ls
```
"""
    expected_s2 = """
# 测试代码块外的$

```bash
$ sudo ls
$ pwd
```

```
$ sudo ls
```
"""
    assert (expected_s2 == convert(s2))

    s3 = """
# 测试说明性文字

#: 这是说明性文字
#: this is also explanatory text
"""

    expected_s3 = """
# 测试说明性文字

这是说明性文字
this is also explanatory text
"""
    assert(expected_s3 == convert(s3))
    return True

def parse_args():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--md', help='To markdown', action='store_true')
    parser.add_argument('--text', help='To text', action='store_true')
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    if args.md:
        renderer = MarkdownRenderer()
    elif args.text:
        renderer = TextRenderer()
    else:
        print('please use --md or --text', file=sys.stderr)
        sys.exit(-1)
    data = sys.stdin.read()
    print(renderer.render(data))
